#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    : /semaphore.py
@Time    : 2021-05-20 16:52:36
@Author  : Gray Snail
@Version : 1.0
@Contact : shtao2011@sina.com
@License : Copyright (c) 2021 Gray Snail
@Desc    : 信号量
'''

from threading import Thread, Semaphore, current_thread
import time
import random

'''

设置一把锁让多个线程同时拿去执行任务。同时拿锁的线程数量就是信号量 Semaphore
计数器的值一定大于0，acquire调用时递减1，为0时则阻塞，直到有其他线程 release
'''


# 信号量大小为3
sem = Semaphore(2)


def fun():
    sem.acquire()
    name = current_thread().getName()
    print(f'{name} 执行')
    time.sleep(random.randint(1, 2))
    sem.release()


if __name__ == '__main__':
    for i in range(5):
        t = Thread(target=fun)
        t.start()
